package com.rongshu.view.mediaPlayer.presenter;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.text.TextUtils;

import com.rongshu.api.RetorfitService;
import com.rongshu.utils.Common;
import com.rongshu.utils.UserInfoUtils;
import com.rongshu.view.base.BaseActivity;
import com.rongshu.view.base.mvp.BasePresenter;
import com.rongshu.view.base.mvp.INetBean;
import com.rongshu.view.discovery.bean.AuthorDetailBean;
import com.rongshu.view.home.entity.ArticleLike;
import com.rongshu.view.home.entity.CommenOneAllDetails;
import com.rongshu.view.home.entity.CommentDetails;
import com.rongshu.view.home.entity.CommentReplysBean;
import com.rongshu.view.home.entity.ShareInformation;
import com.rongshu.view.mediaPlayer.bean.AudiobookDetailsResponse;
import com.rongshu.view.mediaPlayer.bean.PlayEvent;
import com.rongshu.view.mediaPlayer.emnu.MediaState;
import com.rongshu.view.mediaPlayer.emnu.PlayAction;
import com.rongshu.view.mediaPlayer.iview.AudiobookPlayerView;
import com.rongshu.view.mediaPlayer.manager.PlayerManager;
import com.rongshu.view.penpal.bean.PostCommentBody;
import com.rongshu.view.penpal.view.ShareDialogListener;
import com.rongshu.widget.BanyanDialog;
import com.rongshu.widget.ShareBottomDialog;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.utils.NetStatusUtils;
import com.widget.toast.ToastUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import okhttp3.ResponseBody;
import rx.Subscriber;
import rx.functions.Action0;
import rx.functions.Func1;

/**
 * created by zhengweis on 2019/4/28.
 * description：
 */
public class AudiobookPlayingPresenter extends BasePresenter<AudiobookPlayerView> {
    private ShareBottomDialog dialog;

    public AudiobookPlayingPresenter(Context context) {
        super(context);
    }

    /**
     * 毫秒转换为 00：00 几分几秒的格式
     */
    public String timeFormat(int milliSecond) {
        int minute = milliSecond / 1000 / 60;
        int second = milliSecond / 1000 % 60;
        String minuteMsg = minute < 10 ? "0" + String.valueOf(minute) : String.valueOf(minute);
        String secondMsg = second < 10 ? "0" + String.valueOf(second) : String.valueOf(second);
        return minuteMsg + ":" + secondMsg;
    }

    /**
     * 用户主动播放
     */
    public void activeReplay(boolean userPhoneNetwork, final PlayEvent playEvent) {
        if (NetStatusUtils.isWIFI(mContext)) {
            playEvent.setAction(PlayAction.RESUME);
            EventBus.getDefault().post(playEvent);
        } else {
            if (userPhoneNetwork) {
                playEvent.setAction(PlayAction.RESUME);
                EventBus.getDefault().post(playEvent);
            } else {
                BanyanDialog.Builder builder = new BanyanDialog.Builder(mContext);
                builder.setRight("继续播放");
                builder.setLeft("取消");
                builder.setTitle("提示");
                builder.setContent("当前不是WIFI网络\n在线播放将消耗你的网络流量");
                final BanyanDialog dialog = builder.create();
                dialog.setCancelable(false);
                dialog.setCanceledOnTouchOutside(false);
                builder.setDialogOnClick(new BanyanDialog.Builder.onClickListener() {
                    @Override
                    public void leftClickListener() {
                        dialog.dismiss();
                    }

                    @Override
                    public void rightClickListener() {
                        BaseActivity activity = (BaseActivity) mContext;
                        activity.application.setUserPhoneNetwork(true);
                        playEvent.setAction(PlayAction.RESUME);
                        EventBus.getDefault().post(playEvent);
                        dialog.dismiss();
                    }
                });
                dialog.show();
            }
        }
    }

    /**
     * +
     *
     * @param userPhoneNetwork 是否允许使用蜂窝网络
     * @param playEvent        播放事件
     */
    public void checkNetState(boolean userPhoneNetwork, final PlayEvent playEvent) {
        final MediaState mediaState = PlayerManager.getPlayer().getMediaState();
        if (NetStatusUtils.isWIFI(mContext)) {
            if (mediaState != MediaState.COMPLETED) {
                playEvent.setAction(PlayAction.PLAY);
                EventBus.getDefault().post(playEvent);
            }
        } else {
            if (userPhoneNetwork) {
                if (mediaState != MediaState.COMPLETED) {
                    playEvent.setAction(PlayAction.PLAY);
                    EventBus.getDefault().post(playEvent);
                }
            } else {
                BanyanDialog.Builder builder = new BanyanDialog.Builder(mContext);
                builder.setRight("继续播放");
                builder.setLeft("取消");
                builder.setTitle("提示");
                builder.setContent("当前不是WIFI网络\n在线播放将消耗你的网络流量");
                final BanyanDialog dialog = builder.create();
                dialog.setCancelable(false);
                dialog.setCanceledOnTouchOutside(false);
                builder.setDialogOnClick(new BanyanDialog.Builder.onClickListener() {
                    @Override
                    public void leftClickListener() {
                        dialog.dismiss();
                    }

                    @Override
                    public void rightClickListener() {
                        BaseActivity activity = (BaseActivity) mContext;
                        activity.application.setUserPhoneNetwork(true);
                        if (mediaState != MediaState.COMPLETED) {
                            playEvent.setAction(PlayAction.PLAY);
                            EventBus.getDefault().post(playEvent);
                        } else {
                            playEvent.setAction(PlayAction.RESUME);
                            EventBus.getDefault().post(playEvent);
                        }
                        dialog.dismiss();
                    }
                });
                dialog.show();
            }
        }
    }

    public void exitHint() {
        BanyanDialog.Builder builder = new BanyanDialog.Builder(mContext);
        builder.setRight("取消");
        builder.setLeft("是");
        builder.setTitle("提示");
        builder.setContent("是否放弃当前评论");
        final BanyanDialog dialog = builder.create();
        builder.setDialogOnClick(new BanyanDialog.Builder.onClickListener() {
            @Override
            public void leftClickListener() {
                getView().finishThisAct();
                dialog.dismiss();
            }

            @Override
            public void rightClickListener() {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    /**
     * 获取有声文章详情
     *
     * @param audioId
     */
    public void getAudiobookDetails(int audioId) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", UserInfoUtils.getUserId());
        map.put("audioId", audioId);
        RetorfitService.GetAudioArticlesModel(UserInfoUtils.getUserId(), audioId,
                Common.encryptionSign(map)).doOnSubscribe(new Action0() {
            @Override
            public void call() {

            }
        }).compose(getView().<AudiobookDetailsResponse>bindToLife()).subscribe(new Subscriber<AudiobookDetailsResponse>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(AudiobookDetailsResponse object) {
                if (object.getErrCode() == 0 && object.getResponse() != null) {
                    getView().onAudiobookDetails(object.getResponse());
                }
            }
        });
    }

    /**
     * 请求有声文章评论列表
     *
     * @param audioId
     * @param pageIndex
     * @param pageSize
     */
    public void getAudiobookComment(int audioId, int pageIndex, int pageSize) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", UserInfoUtils.getUserId());
        map.put("audio_id", audioId);
        map.put("Sort", 0);
        map.put("pageIndex", pageIndex);
        map.put("pageSize", pageSize);
        RetorfitService.getAudioArticleComment(UserInfoUtils.getUserId(), audioId, 0,
                pageIndex, pageSize, Common.encryptionSign(map))
                .map(new Func1<CommentDetails, List<CommentDetails.ResponseBean>>() {
                    @Override
                    public List<CommentDetails.ResponseBean> call(CommentDetails commentDetails) {
                        return commentDetails.getResponse();
                    }
                })
                .compose(getView().<List<CommentDetails.ResponseBean>>bindToLife())
                .subscribe(new Subscriber<List<CommentDetails.ResponseBean>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(List<CommentDetails.ResponseBean> responseBeanList) {
                        if (responseBeanList != null) {
                            getView().onCommentMsg(responseBeanList);
                        }
                    }
                });
    }

    /**
     * 发送评论、回复
     */
    public void audiobookPostCommentOrReplyAdd(LinkedHashMap<String, AuthorDetailBean> authorDetailBeanMap, String content,
                                               int audioId, int comment_id, int reply_id) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", UserInfoUtils.getUserId());
        map.put("audioId", audioId);
        map.put("comment_id", comment_id);
        map.put("reply_id", reply_id);
        PostCommentBody body = new PostCommentBody();
        body.setContents(content);
        StringBuilder aiteStrsb = new StringBuilder();
        for (Map.Entry<String, AuthorDetailBean> entry : authorDetailBeanMap.entrySet()) {
            if (!TextUtils.isEmpty(aiteStrsb)) {
                aiteStrsb.append(",");
            }
            aiteStrsb.append(entry.getValue().getUser_id_to());
        }
        body.setAiteStr(aiteStrsb.toString());
        RetorfitService.audiobookPostCommentOrReplyAdd(UserInfoUtils.getUserId(), audioId, comment_id, reply_id,
                Common.encryptionSign(map), body).doOnSubscribe(new Action0() {
            @Override
            public void call() {

            }
        }).compose(getView().<ResponseBody>bindToLife()).subscribe(new Subscriber<ResponseBody>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(ResponseBody object) {
                getView().commentSuccess(object);
            }
        });
    }

    /**
     * 收藏/取消收藏 有声文章
     *
     * @param content_id
     */
    public void collectionAudiobook(int content_id) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", UserInfoUtils.getUserId());
        map.put("type", 3);
        map.put("content_id", content_id);
        RetorfitService.getIsCollect(UserInfoUtils.getUserId(), 3, content_id, Common.encryptionSign(map))
                .compose(getView().<INetBean>bindToLife())
                .subscribe(new Subscriber<INetBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(INetBean iNetBean) {
                        if (iNetBean.getErrCode() == 0) {
                            getView().onCollectSuccess();
                        }
                    }
                });
    }

    /**
     * 文章点赞
     *
     * @param content_id
     */

    public void getLike(int content_id) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", UserInfoUtils.getUserId());
        map.put("type", "voice");
        RetorfitService.getlike(content_id, UserInfoUtils.getUserId(), "voice", Common.encryptionSign(map))
                .compose(getView().<ArticleLike>bindToLife())
                .subscribe(new Subscriber<ArticleLike>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(ArticleLike iNetBean) {
                        if (iNetBean.getErrCode() == 0) {
                            getView().onPraiseSuccess();
                        }
                    }
                });
    }

    /**
     * 文章取消点赞
     *
     * @param content_id
     */
    public void getOffLike(int content_id) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", UserInfoUtils.getUserId());
        map.put("type", "voice");
        map.put("contribute_id", content_id);
        RetorfitService.getOfflike(UserInfoUtils.getUserId(), "voice", content_id, Common.encryptionSign(map))
                .compose(getView().<ArticleLike>bindToLife())
                .subscribe(new Subscriber<ArticleLike>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(ArticleLike iNetBean) {
                        if (iNetBean.getErrCode() == 0) {
                            getView().onPraiseSuccess();
                        }
                    }
                });
    }


    /**
     * 请求 分享有声文章  数据
     *
     * @param contribute_id
     * @param position
     */
    public void shareAudiobook(int contribute_id, final SHARE_MEDIA position) {
        Map<String, Object> map = new HashMap<>();
        map.put("type", 2);
        map.put("contribute_id", contribute_id);
        map.put("type_id", 3);
        map.put("user_id", UserInfoUtils.getUserId());
        map.put("penpalwill_id", 0);
        RetorfitService.getShareInformation(2, contribute_id, 3,
                UserInfoUtils.getUserId(), 0, Common.encryptionSign(map))
                .compose(getView().<ShareInformation>bindToLife())
                .subscribe(new Subscriber<ShareInformation>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(ShareInformation shareBean) {
                        if (shareBean.getErrCode() == 0) {
                            requestShare(position, shareBean);
                        } else {
                            ToastUtils.show(shareBean.getErrMsg());
                        }
                    }
                });
    }

    /**
     * 获取单个评论下的所有回复
     */
    public void getOnecommentDetail(int comment_id, int pageIndex, int pageSize) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", UserInfoUtils.getUserId());
        map.put("comment_id", comment_id);
        map.put("pageIndex", pageIndex);
        map.put("pageSize", pageSize);
        RetorfitService.getOnecommentDetail(UserInfoUtils.getUserId(), comment_id, pageIndex, pageSize, Common.encryptionSign(map))
                .map(new Func1<CommenOneAllDetails, List<CommentReplysBean>>() {
                    @Override
                    public List<CommentReplysBean> call(CommenOneAllDetails commenOneAllDetails) {
                        return commenOneAllDetails.getComment_replys();
                    }
                })
                .map(new Func1<List<CommentReplysBean>, List<CommentReplysBean>>() {
                    @Override
                    public List<CommentReplysBean> call(List<CommentReplysBean> commentReplysBeans) {
                        for (CommentReplysBean commentReplysBean : commentReplysBeans) {
                            commentReplysBean.setAvatar(commentReplysBean.getFrom_avatar());
                            commentReplysBean.setVip(commentReplysBean.isFrom_vip());
                        }
                        return commentReplysBeans;
                    }
                })
                .compose(getView().<List<CommentReplysBean>>bindToLife())
                .subscribe(new Subscriber<List<CommentReplysBean>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(List<CommentReplysBean> commentReplysBeans) {
                        getView().onOnecommentDetail(commentReplysBeans);
                    }
                });
    }

    /**
     * 评论点赞（任何评论）
     */
    public void getCommentlike(int obj_id, int comment_id) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", UserInfoUtils.getUserId());
        map.put("type", 3);
        map.put("obj_id", obj_id);
        map.put("comment_id", comment_id);
        RetorfitService.getCommentlike(UserInfoUtils.getUserId(), 3, obj_id, comment_id, Common.encryptionSign(map))
                .compose(getView().<INetBean>bindToLife())
                .subscribe(new Subscriber<INetBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(INetBean iNetBean) {
                        ToastUtils.show(iNetBean.getErrMsg());
                        if (iNetBean.getErrCode() == 0) {
                            getView().onCommentlike();
                        }
                    }
                });
    }

    /**
     * 删除该条评论提示
     */
    public void deleteCommentDeleteDialog(final int audio_id, final int comment_id, final int reply_id) {
        BanyanDialog.Builder builder = new BanyanDialog.Builder(mContext);
        builder.setTitle("确认要删除该条评论吗？")
                .setLeft("取消")
                .setRight("确定");
        final BanyanDialog dialog = builder.create();
        builder.setDialogOnClick(new BanyanDialog.Builder.onClickListener() {
            @Override
            public void leftClickListener() {
                dialog.dismiss();
            }

            @Override
            public void rightClickListener() {
                dialog.dismiss();
                audiobookCommentOrReplyDelete(audio_id, comment_id, reply_id);
            }
        });
        dialog.show();
    }

    /**
     * 帖子评论删除/帖子回复删除
     */
    public void audiobookCommentOrReplyDelete(int audio_id, int comment_id, int reply_id) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", UserInfoUtils.getUserId());
        map.put("audio_id", audio_id);
        map.put("comment_id", comment_id);
        map.put("reply_id", reply_id);
        RetorfitService.audiobookCommentOrReplyDelete(UserInfoUtils.getUserId(), audio_id, comment_id, reply_id, Common.encryptionSign(map))
                .compose(getView().<INetBean>bindToLife())
                .subscribe(new Subscriber<INetBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(INetBean bean) {
                        getView().onCommentDelete(bean);
                    }
                });
    }

    /**
     * 分享到第三方
     */
    public void share(final int contribute_id) {
        ShareBottomDialog.Builder builder = new ShareBottomDialog.Builder(mContext);
        dialog = builder.setSharePositionListener(new ShareDialogListener() {
            @Override
            public void onShareClick(DialogInterface dialog, SHARE_MEDIA position) {
                shareAudiobook(contribute_id, position);
            }
        }).create();
        dialog.show();
    }

    private void requestShare(SHARE_MEDIA type, ShareInformation shareBean) {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        final UMWeb web = new UMWeb(shareBean.getResponse().getShare_link());
        web.setTitle(shareBean.getResponse().getTitle());//标题
        web.setThumb(new UMImage(mContext, shareBean.getResponse().getImg()));  //缩略图
        web.setDescription(shareBean.getResponse().getContent());//描述
        new ShareAction((Activity) mContext)
                .setPlatform(type)//传入平台
                .withMedia(web)
                .setCallback(new UMShareListener() {
                    @Override
                    public void onStart(SHARE_MEDIA share_media) {

                    }

                    @Override
                    public void onResult(SHARE_MEDIA share_media) {
                    }

                    @Override
                    public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                        ToastUtils.show(throwable.getMessage());
                    }

                    @Override
                    public void onCancel(SHARE_MEDIA share_media) {
                        ToastUtils.show("分享取消");
                    }
                })
                .share();
    }
}
